<template>
  <div class="amazon-shop-list-wrap table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getShopList">
        <template #headerLeft>
          <a-space>
            <p>账号总计 {{ pageNation.total }}</p>
            <p style="margin-right: 30px">店铺总计 {{ marketNum }}</p>
            <a-button v-if="$authPass('user.shop.save')" type="primary" size="medium" @click="showAddShopDialog = true">新增店铺</a-button>
            <a-button v-if="$authPass('user.shop.edit')" class="gray-outline" size="medium" @click="openSetMasters">设置店长</a-button>
            <a-button v-if="$authPass('user.shop.edit')" class="gray-outline" size="medium" @click="openChooseSales">设置店员</a-button>
            <a-button v-if="$authPass('user.shop.edit')" class="gray-outline" size="medium" @click="openChooseBrand">关联品牌</a-button>
            <a-button v-if="$authPass('user.shop.edit')" class="gray-outline" size="medium" @click="batchChangeStatus(selectMarketRow, 0)">批量停用</a-button>
            <a-button v-if="$authPass('user.shop.edit')" class="gray-outline" size="medium" @click="batchChangeStatus(selectMarketRow, 1)">批量启用</a-button>
            <a-button class="gray-outline" v-if="userStore && userStore.companyId == 'yfn' && $authPass('user.shop.edit')" size="medium" @click="showSyncDialog = true">同步ERP店铺</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table ref="tableListRef" class="table-singe-line" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @select-all="selectAll" @select="selectRowChange" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :columns="tableColumns" :data="shopList" size="mini" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.title === 'SellerID'" #cell="{ record }">
                  <p class="highlight">{{ record.sellerId }}</p>
                </template>
                <template v-else-if="item.title === '品牌'" #cell="{ record }">
                  <p>{{ showBrandName(record) }}</p>
                </template>
                <template v-else-if="item.title === '店长'" #cell="{ record }">
                  <p>{{ showShopMastersName(record.shopMasters) }}</p>
                </template>
                <template v-else-if="item.title === '基础API授权'" #cell="{ record }">
                  <div class="flex-c">
                    <p :class="{ warningColor: record.baseAuth === -1 }">{{ baseAuthMap[record.baseAuth] }}</p>
                    <p style="margin-left: 10px" class="cursor highlight" v-if="record.baseAuth != 1 && $authPass('user.shop.edit')" @click="toAPIAuth(record)">{{ record.baseAuth === -1 ? '重新授权' : '去授权' }}</p>
                  </div>
                </template>
                <template v-else-if="item.title === '授权时间'" #cell="{ record }">
                  <p>{{ $setTime(record.gmtBaseAuth) }}</p>
                </template>
                <template v-else-if="item.title === '创建时间'" #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate) }}</p>
                </template>
                <template v-else-if="item.title === '操作'" #cell="{ record }">
                  <a-space>
                    <a-button type="text" size="mini" @click="openEditShop(record)" v-if="$authPass('user.shop.edit')">编辑</a-button>
                  </a-space>
                </template>
                <template v-else #cell="{ record }">
                  {{ record[item.dataIndex] }}
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <ul class="flex-wrap markets-wrap">
                <li class="markets-item" v-for="(shopMarkets, i) in record.shopMarkets" :key="i">
                  <p>站点：{{ shopMarkets.marketplaceName }}({{ shopMarkets.marketplaceCode }}) ({{ shopMarkets.currency }})</p>
                  <p>
                    <span>广告授权：</span>
                    <span class="cursor highlight" v-if="shopMarkets.cpcAuth === 0 && $authPass('user.shop.edit')" @click="toAdAuth(shopMarkets)">去授权</span>
                    <template v-else-if="shopMarkets.cpcAuth === 1">
                      <span>{{ baseAuthMap[shopMarkets.cpcAuth] }} </span>
                      <span>{{ $setTime(shopMarkets.gmtCpcAuth) }}</span>
                    </template>
                    <template v-else>
                      <span class="warningColor">{{ baseAuthMap[shopMarkets.cpcAuth] }} </span>
                      <span class="cursor highlight" v-if="$authPass('user.shop.edit')" @click="toAdAuth(shopMarkets)">重新授权</span>
                    </template>
                    <span></span>
                  </p>
                  <p>店员：{{ showShopMastersName(shopMarkets.shopClerks) }}</p>
                  <p>
                    <span>状态：</span>
                    <a-popconfirm :content="`确定是否${shopMarkets.status ? '停用' : '开启'}?`" @ok="changeStatus([shopMarkets.id], shopMarkets.status ? 0 : 1)" type="error">
                      <a-switch size="small" :disabled="!$authPass('user.shop.edit')" v-model="shopMarkets.status" :beforeChange="handleChangeIntercept" :checked-value="1" :unchecked-value="0">
                        <template #checked> 开 </template>
                        <template #unchecked> 关 </template>
                      </a-switch>
                    </a-popconfirm>
                  </p>
                  <a-checkbox v-model="shopMarkets.checked" @change="changeMarketChecked($event, shopMarkets)" />
                </li>
                <li class="add-item" @click="openAddMarket(record)" v-if="$authPass('user.shop.save')">
                  <icon-plus />
                  <p>新增站点</p>
                </li>
              </ul>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 关联品牌 -->
  <ChooseBrand v-if="showChooseBrandDialog" :idList="selectRow" :isShow="showChooseBrandDialog" @closed="showChooseBrandDialog = false" @success="getShopList" />
  <!-- 设置店长 -->
  <ChooseUser v-if="showChooseUserDialog" :multiple="false" :isShow="showChooseUserDialog" title="设置店长" label="选择店长" :isRequired="true" @closed="showChooseUserDialog = false" @success="setMaster" />
  <!-- 添加店铺 -->
  <AddShop v-if="showAddShopDialog" :isShow="showAddShopDialog" @closed="showAddShopDialog = false" @success="getShopList" />
  <!-- 选择店员 -->
  <ChooseSales v-if="showChooseSales" :idList="selectMarketRow" :isShow="showChooseSales" @closed="showChooseSales = false" @success="getShopList" />
  <!-- 编辑店铺 -->
  <EditShop v-if="showEditShopDialog" :shopId="currentData.id" :isShow="showEditShopDialog" @closed="showEditShopDialog = false" @success="getShopList" />
  <!-- 添加站点 -->
  <AddMarket v-if="showAddMarketDialog" :isShow="showAddMarketDialog" :shops="currentData" @closed="showAddMarketDialog = false" @success="getShopList" />
  <!-- 同步ERP店鋪 -->
  <SyncErpShop v-if="showSyncDialog" :isShow="showSyncDialog" @closed="showSyncDialog = false" @success="getShopList" />
</template>
<script lang="ts" setup>
  import { defineComponent, ref, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import AddShop from './components/addShop.vue'
  import AddMarket from './components/addMarket.vue'
  import ChooseSales from './components/chooseSales.vue'
  import EditShop from './components/editShop.vue'
  import ChooseUser from '@/components/ChooseUser.vue'
  import ChooseBrand from './components/chooseBrand.vue'
  import SyncErpShop from './components/syncErpShop.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'
  import { findShopPageByParam, countShopMarketByParam, updateShopBase, updateShopMarketBatch, getAmazonPiiAuthUrl, getAmazonAdAuthUrl } from '@/api/system'
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopName',
      label: '店铺名称',
      width: 180,
      value: ref(),
      type: 'input_search',
    },
    {
      key: 'sellerId',
      label: 'SellerID',
      width: 180,
      value: ref(),
      type: 'input_search',
    },
    {
      key: 'masterName',
      label: '店长',
      width: 180,
      value: ref(),
      type: 'input_search',
    },
    {
      key: 'baseAuth',
      label: '基础API授权',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '正常',
          value: '1',
        },
        {
          label: '异常',
          value: '-1',
        },
        {
          label: '未授权',
          value: '0',
        },
      ],
    },
    {
      key: 'cpcAuth',
      label: '广告授权',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '正常',
          value: '1',
        },
        {
          label: '异常',
          value: '-1',
        },
        {
          label: '未授权',
          value: '0',
        },
      ],
    },
    {
      key: 'brandName',
      label: '品牌',
      width: 180,
      value: ref(),
      type: 'input_search',
    },
  ])
  const expandable = reactive<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tableColumns: Array<any> = [
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      width: 180,
    },
    {
      title: 'SellerID',
      dataIndex: 'sellerId',
      width: 140,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 180,
    },
    {
      title: '地区',
      dataIndex: 'region',
      width: 100,
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      width: 100,
    },
    {
      title: '店长',
      dataIndex: 'shopUser',
      width: 80,
    },
    {
      title: '基础API授权',
      dataIndex: 'baseAuth',
      width: 100,
    },
    {
      title: '授权时间',
      dataIndex: 'gmtBaseAuth',
      width: 140,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      width: 140,
    },
    {
      title: '操作',
      dataIndex: '编辑',
      width: 80,
    },
  ]
  const baseAuthMap: any = reactive({
    '0': '未授权',
    '1': '已授权',
    '-1': '授权异常',
  })
  let pageNation = ref({ pageSize: 20, pageNum: 1, total: 0 }) //分页
  const tableLoading = ref(false)
  const shopList = ref([]) //用户列表
  const marketNum = ref(0)
  const showAddShopDialog = ref(false)
  const showChooseUserDialog = ref(false)
  const showAddMarketDialog = ref(false)
  const showChooseSales = ref(false)
  const showChooseBrandDialog = ref(false)
  const showEditShopDialog = ref(false)
  const selectRow = ref([])
  const selectMarketRow = ref([])
  const currentData = ref<any>({})
  const userStore = useUserStore()
  const showSyncDialog = ref(false)
  const tableListRef = ref()
  const selectColumn = (val: any) => {
    selectRow.value = val
  }
  function selectRowChange(keys: Array<string | number>, key: string | number, data: any) {
    data.shopMarkets.forEach((el: any) => {
      el.checked = keys.indexOf(key) > -1 ? true : false
      changeMarketChecked(el.checked, el)
    })
  }
  function selectAll(val: boolean) {
    shopList.value.forEach((item: any) => {
      item.shopMarkets.forEach((el: any) => {
        el.checked = val
        changeMarketChecked(el.checked, el)
      })
    })
  }
  // 分页
  function changePage(val: number) {
    pageNation.value.pageNum = val
    getShopList()
  }
  function sizeChange(val: number) {
    pageNation.value.pageSize = val
    getShopList()
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    pageNation.value.pageNum = 1
    let filterData = JSON.parse(JSON.stringify(info)) || {}
    getShopList(filterData)
  }
  // 获取店铺列表
  async function getShopList(filterData?: any) {
    let params = {
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
      ...filterData,
    }
    tableLoading.value = true
    const res: any = await findShopPageByParam(params)
    tableListRef.value.selectAll(false)
    selectMarketRow.value = []
    tableLoading.value = false
    shopList.value = res?.data?.records || []
    expandable.expandedRowKeys = shopList.value.map((el: any) => el.id)
    pageNation.value.total = res?.data?.total || 0

    // 查询站点数量
    getMarketByParam(params)
  }
  getShopList()

  // 查询站点数量
  async function getMarketByParam(params: any) {
    const res: any = await countShopMarketByParam(params)
    marketNum.value = res?.data || 0
  }
  // 选择站点
  function changeMarketChecked(val: any, item: any) {
    let _id = item.id as never
    if (val) {
      selectMarketRow.value.push(_id)
    } else {
      const _index = selectMarketRow.value.indexOf(_id)
      if (_index > -1) {
        selectMarketRow.value.splice(_index, 1)
      }
    }
  }

  // 显示品牌名称
  function showBrandName(item: any) {
    return item?.shopBrands?.map((el: any) => el.brandName)?.join(',')
  }
  // 显示店长信息
  function showShopMastersName(userList: any) {
    return userList?.map((el: any) => el.userName)?.join(',')
  }
  // 打开设置店长
  function openSetMasters() {
    if (!selectRow.value?.length) {
      return Message.error('请选择需要操作的店铺')
    }
    showChooseUserDialog.value = true
  }
  // 设置店长
  async function setMaster(user: any) {
    const res: any = await updateShopBase({
      idList: selectRow.value,
      shopMasterIds: [user],
    })
    if (res) {
      Message.success('店长设置成功！')
      getShopList()
    }
  }
  // 打开设置品牌
  function openChooseBrand() {
    if (!selectRow.value?.length) {
      return Message.error('请选择需要操作的店铺')
    }
    showChooseBrandDialog.value = true
  }
  // 打开选择店员
  function openChooseSales() {
    if (!selectMarketRow.value?.length) {
      return Message.error('请选择需要操作的站点')
    }
    showChooseSales.value = true
  }
  // 打开编辑店铺
  function openEditShop(item: any) {
    currentData.value = item
    showEditShopDialog.value = true
  }
  // 打开新增站点
  function openAddMarket(shops: any) {
    currentData.value = shops
    showAddMarketDialog.value = true
  }
  // 批量修改状态
  async function batchChangeStatus(idList: Array<string>, status: any) {
    if (!idList?.length) {
      return Message.error('请选择需要操作的站点')
    }
    let text = status === 1 ? '启用' : '停用'
    Modal.confirm({
      title: '提示',
      content: `请再次确认，${text}选中的站点`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        changeStatus(idList, status)
      },
    })
  }
  // 修改状态
  async function changeStatus(idList: Array<string>, status: any) {
    const res: any = await updateShopMarketBatch({
      idList: idList,
      status: status,
    })
    if (res) {
      Message.success('修改成功！')
      getShopList()
    }
  }
  // API授权
  async function toAPIAuth(item: any) {
    const res: any = await getAmazonPiiAuthUrl({ id: item.id })
    let authUrl = res?.data
    if (authUrl) {
      window.open(authUrl, '_block')
    }
  }
  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 广告授权
  async function toAdAuth(item: any) {
    const res: any = await getAmazonAdAuthUrl({ marketplaceIds: item.marketplaceId })
    let adAuthUrlMap = res?.data || {}
    let authUrl = adAuthUrlMap[item.marketplaceId]
    if (authUrl) {
      window.open(authUrl, '_block')
    }
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'AmazonShop',
  })
</script>
<style lang="less" scoped>
  :deep(.arco-table-element) {
    border-collapse: collapse;
    border-top: 1px solid #ddd;
  }
  :deep(.arco-table-td) {
    background-color: transparent;
    border-top: 1px solid #ddd;
    border-bottom: none;
  }

  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-table-tr) {
    border-left: 1px solid #ddd;
    border-right: 1px solid #ddd;
    background-color: #f1f1f1;
    &:hover {
      .arco-table-td {
        background-color: transparent !important;
      }
    }
  }
  :deep(.arco-table-tr-expand) {
    border-left: none !important;
    border-right: none !important;
    &:hover {
      .arco-table-td {
        background-color: #fff !important;
      }
      .arco-table-cell {
        background-color: var(--color-fill-1) !important;
      }
    }
    .arco-table-td {
      background-color: #fff;
      padding: 0;
      position: relative;
      left: -1px;
    }
    .arco-table-cell {
      margin-bottom: 10px;
      border-bottom: 1px solid #ddd;
      border-left: 1px solid #ddd;
      border-right: 1px solid #ddd;
    }
  }
  .markets-wrap {
    padding: 10px 20px;
    .markets-item {
      border: 1px solid var(--color-border);
      padding: 5px 10px;
      margin-right: 10px;
      width: 220px;
      position: relative;
      color: #666;
      .arco-checkbox {
        position: absolute;
        top: 10px;
        right: 10px;
      }
    }
  }
  .add-item {
    width: 100px;
    border: 1px solid var(--color-border);
    font-size: 12px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    color: #999;
    cursor: pointer;
    .arco-icon {
      font-size: 20px;
      margin-bottom: 4px;
    }
  }
</style>
